package com.starsoft.quant.strategy;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import com.starsoft.quant.bean.ModelContext;
import com.starsoft.quant.bean.QuantDetail;
import com.starsoft.quant.bean.QuantDetailId;
import com.starsoft.quant.bean.QuantSummary;
import com.starsoft.quant.bean.QuantSummaryId;
import com.starsoft.quant.executor.ExecutorContext;
import com.starsoft.quant.executor.StrategyReport;
import com.starsoft.smdc.bean.SmdcMarketDaily;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.trade.bean.TradeAcountStatus;
import com.starsoft.trade.bean.TradePosition;

public abstract class StrategyImpl implements Strategy {

	protected ExecutorContext context;
	
	protected ModelContext modelContext;

	public void setContext(ExecutorContext context) {
		this.context = context;
		this.modelContext = context.getModelContext();
	}
	
	public StrategyReport createReport(List<QuantDetail> details){
		Integer acountId = context.getModelContext().getAcountId();
		double avg=0;
		
		if (!details.isEmpty()) {
			for (QuantDetail report : details) {
				avg += report.getRating();
			}
			avg = avg / details.size();
		}

		QuantSummaryId summaryId = new QuantSummaryId(acountId, context.getCurrentDate());
		QuantSummary summary = new QuantSummary(summaryId);
		summary.setAvgRating(avg);
		summary.setRunTime(new Timestamp(new Date().getTime()));
		
		StrategyReport strategyReport = new StrategyReport();
		strategyReport.setSummary(summary);
		strategyReport.setDetails(details);
		return strategyReport;
	}

	protected QuantDetail createDetail(SmdcSecurity security, Double rating) {		
		Integer acountId = context.getModelContext().getAcountId();
		String secId=security.getSecId();
		SmdcMarketDaily market = context.getMarket(secId);
		TradeAcountStatus status = context.getAcountStatus();
		TradePosition position = status.getPosition(secId);
		Integer secNum = null;
		if(position != null && position.getSecNum()!=null){
			secNum = position.getSecNum().intValue();
		}
		
		QuantDetailId id = new QuantDetailId(acountId,context.getCurrentDate(),secId);		
		QuantDetail detail = new QuantDetail(id);
		detail.setPrice(market.getClosePrice());
		detail.setPriceChp(market.getPercent());
		detail.setPosition(secNum);
		detail.setRating(rating);
		detail.setIsOpen(market.getIsOpen());
		return detail;
	}
	
	public ExecutorContext getStrategyContext() {
		return context;
	}

	public void setStrategyContext(ExecutorContext strategyContext) {
		this.context = strategyContext;
	}
	
}
